<?php
// 应用公共文件
/**
 * 验证手机号码
 * */
function valid_phone($phone){
    return preg_match('/^1\d{10}$/',$phone);
}
function valid_email($email){
    return preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/',$email);
}

function file_abs_path($file){
    $path = $file;
    if(stripos($path,'http')!==false){
        $ex_arr = explode('/',$path);
        $all_arr=array_slice($ex_arr,3);
        $path = root_path().implode('/',$all_arr);
    }
    return $path;
}

//计算距离信息
function cal_distance_info($lng_lat_one,$lng_lat_two)
{

    $lng_lat_one  = explode(',',$lng_lat_one);
    $lng_lat_two  = explode(',',$lng_lat_two);
    $data['distance'] = 0;
    $data['distance_second'] = 0;
    $data['distance_time'] = '';
    $data['distance_full_time'] = '';
    if(
        (count($lng_lat_one)==2 && $lng_lat_one[0]>0 && $lng_lat_one[1]>0) &&
        (count($lng_lat_two)==2 && $lng_lat_two[0]>0 && $lng_lat_two[1]>0)
    ){
        $distance = get_distance($lng_lat_one[0],$lng_lat_one[1],$lng_lat_two[0],$lng_lat_two[1]);
        $distance_second = dis_transferred_second($distance);
        $data['distance'] = empty($distance)?0:$distance;
        $data['distance_second'] = $distance_second;
        $data['distance_time'] = next_time($distance_second);
        $data['distance_full_time'] = time()+$distance_second;
    }
    return $data;
}

/**
 * 距离换算时间
 * @param $dis int 距离(m)
 * @param $speed int 速度 m/s
 * @return Int
 * */
function dis_transferred_second($dis,$speed=2) {
    return intval($dis/$speed);
}


//秒转化
function next_time($second) {
    if($second<=60*1){
        $second = 60;
    }
    $next_time = strtotime('+ '.$second.' seconds');
    $current_day = date('Y-m-d');
    if($current_day==date('Y-m-d',$next_time)){
        return date('H:i',$next_time);
    }else{
        return date('Y-m-d H:i',$next_time);
    }
}
/**
 * 计算两点地理坐标之间的距离
 * @param Decimal $longitude1 起点经度
 * @param Decimal $latitude1 起点纬度
 * @param Decimal $longitude2 终点经度
 * @param Decimal $latitude2 终点纬度
 * @param Int   $unit    单位 1:米 2:公里
 * @param Int   $decimal  精度 保留小数位数
 * @return Decimal
 */
function get_distance($longitude1, $latitude1, $longitude2, $latitude2, $unit=1, $decimal=2){

    $EARTH_RADIUS = 6370.996; // 地球半径系数
    $PI = 3.1415926;

    $radLat1 = $latitude1 * $PI / 180.0;
    $radLat2 = $latitude2 * $PI / 180.0;

    $radLng1 = $longitude1 * $PI / 180.0;
    $radLng2 = $longitude2 * $PI /180.0;

    $a = $radLat1 - $radLat2;
    $b = $radLng1 - $radLng2;

    $distance = 2 * asin(sqrt(pow(sin($a/2),2) + cos($radLat1) * cos($radLat2) * pow(sin($b/2),2)));
    $distance = $distance * $EARTH_RADIUS * 1000;

    if($unit==2){
        $distance = $distance / 1000;
    }
//    dump($distance,$unit,number2dot($distance, $decimal));exit;
    return number2dot($distance, $decimal);

}

//计算距离信息
function m_to_distance_unit($distance)
{
    if(empty($distance) || $distance<0){
        return ['--','km'];
    }
    if($distance<1000){
        $unit = 'm';
    }else{
        $unit = 'km';
        $distance = $distance/1000;
    }
    return [(string)round($distance,1),$unit];

}

//保留小数-只舍不入
function number2dot($number,$dot=2,$is_up = 2)
{
    $exp = pow(10,$dot);
    if($is_up==1){ //
        $number = (ceil($number*$exp))/$exp;
    }else if($is_up==2){
        $number = (floor($number*$exp))/$exp;
    }else{
        $number =  (round($number*$exp))/$exp;
    }
    return sprintf('%.'.$dot.'f',$number);
}


//本周日期
function get_current_week()
{
    //当前日期
    $sdefaultDate = date("Y-m-d");
//$first =1 表示每周星期一为开始日期 0表示每周日为开始日期
    $first=1;
//获取当前周的第几天 周日是 0 周一到周六是 1 - 6
    $w=date('w',strtotime($sdefaultDate));
//获取本周开始日期，如果$w是0，则表示周日，减去 6 天
    $week_start=date('Y-m-d',strtotime("$sdefaultDate -".($w ? $w - $first : 6).' days'));
//本周结束日期
    $week_end=date('Y-m-d',strtotime("$week_start +6 days"));
    $date = [$week_start];
    for($i=1;$i<7;$i++){
        $date[] = date('Y-m-d',strtotime("$week_start +$i days"));
    }
    return $date;
}

function day_week($date)
{
    $strtotime = strtotime($date);
    if(empty($strtotime)){
        return '';
    }
    $weekarray=array("日","一","二","三","四","五","六"); //先定义一个数组
    return $weekarray[date('w',$strtotime)];
}


//获取时间
function get_op_time($date_mode)
{
    $start_time = strtotime(date('Y-m-d'));
    $time_mode = 'day';
    $day_format = 'Y-m-d';
    $start_i = 1;
    if ( $date_mode == 'day' ) { //按小时计算
        $last_time = 24;
        $time_mode = 'hours';
        $day_format = 'H';
        $start_i = 0;
    } elseif ( $date_mode == 'week' ) {
        $last_time = 7;
        $start_time -= $last_time*86400;
    } elseif ( $date_mode == 'month' ) {
        $last_time = 30;
        $start_time -= $last_time*86400;
    }  elseif ( $date_mode == 'month60' ) {
        $last_time = 60;
        $start_time -= $last_time*86400;
    } elseif ( $date_mode == 'year' ) {
        $last_time = 365;
        $start_time -= $last_time*86400;
    }
    $data = [];
    for ($i=$start_i; $i<=$last_time; $i++){
        $data[] = date($day_format,strtotime('+'.$i.' '.$time_mode,$start_time));
    }

    return $data;
}

//验证时间
function check_date($date){
    $bool = true;
    if(!preg_match ('@^[0-9][0-9/-: ]*[0-9]$@', $date, $parts)){
        $bool = false;
    }
    return $bool;
}

//计算时间
function time_tranx($the_time)
{
    $now_time = time();
    $dur = $now_time - $the_time;
    if ($dur <= 0) {
        $mas =  '刚刚';
    } else {
        if ($dur < 60) {
            $mas =  $dur . '秒前';
        } else {
            if ($dur < 3600) {
                $mas =  floor($dur / 60) . '分钟前';
            } else {
                if ($dur < 86400) {
                    $mas =  floor($dur / 3600) . '小时前';
                } else {
                    if ($dur < 259200) { //3天内
                        $mas =  floor($dur / 86400) . '天前';
                    } else {
                        $mas =  date("Y-m-d H:i:s",$the_time);
                    }
                }
            }
        }
    }
    return $mas;
}


/**
 *   将数组转换为xml
 *    @param array $data    要转换的数组
 *   @param bool $root     是否要根节点
 *   @return string         xml字符串
 *    @author Dragondean
 *    @url    http://www.cnblogs.com/dragondean
 */
function arr2xml($data, $root = true){
    $str="";
    if($root)$str .= "<xml>";
    foreach($data as $key => $val){
        if(is_array($val)){
            $child = arr2xml($val, false);
            $str .= "<$key>$child</$key>";
        }else{
            $str.= "<$key>$val</$key>";
        }
    }
    if($root)$str .= "</xml>";
    return $str;
}


function filesize_to_alias(int $filesize,$unit="MB")
{
    if($filesize<=0){
        return 0;
    }
    $result = $filesize/1024;
    if($unit=="MB"){
        $result = $result/1024;
    }
    return sprintf('%.2f',$result);
}

//计算距离
function cal_distance()
{
    return '0km';
}


function cal_duration($duration)
{
    if(empty($duration) || !is_numeric($duration) || $duration<0){
        return '00:00';
    }

    $minute = floor($duration/60);
    $second = $duration%60;
    return sprintf('%02d:%02d',$minute,$second);
}

function create_guid($namespace = '') {
    static $guid = '';
    $uid = uniqid("", true);
    $data = $namespace;
    $data .= $_SERVER['REQUEST_TIME']??'';
    $data .= $_SERVER['HTTP_USER_AGENT']??'';
    $data .= $_SERVER['LOCAL_ADDR']??'';
    $data .= $_SERVER['LOCAL_PORT']??'';
    $data .= $_SERVER['REMOTE_ADDR']??'';
    $data .= $_SERVER['REMOTE_PORT']??'';
    $hash = strtoupper(hash('ripemd128', $uid . $guid . md5($data)));
    $guid =
        substr($hash, 0, 6) .
        '-' .
        substr($hash, 8, 4) .
        '-' .
        substr($hash, 12, 4) .
        '-' .
        substr($hash, 16, 4) .
        '-' .
        substr($hash, 20, 10);
    return $guid;
}

//获取颜色对象
function get_color_objects(){
    return [
        ['name'=>'红色','name_en'=>'Red','color'=>'red'],
        ['name'=>'橙色','name_en'=>'Orange','color'=>'orange'],
        ['name'=>'黄色','name_en'=>'Yellow','color'=>'yellow'],
        ['name'=>'绿色','name_en'=>'Green','color'=>'green'],
        ['name'=>'蓝色','name_en'=>'Blue','color'=>'blue'],
        ['name'=>'紫色','name_en'=>'Purple','color'=>'purple'],
        ['name'=>'灰色','name_en'=>'Coffee','color'=>'coffee'],
        ['name'=>'黑色','name_en'=>'Black','color'=>'black'],
        ['name'=>'白色','name_en'=>'White','color'=>'white'],
    ];
}

//获取颜色对象
function get_size_objects(){
    return [
        ['name'=>'XS'],
        ['name'=>'S'],
        ['name'=>'M'],
        ['name'=>'L'],
        ['name'=>'XL'],
        ['name'=>'XXL'],
        ['name'=>'XXXL'],
        ['name'=>'XXXXL'],
    ];
}

function get_color_name($h,$s,$v) {
    //误差率2%
    if($s>=15 && $v>=25){
        //有饱和度&有亮度 =有颜色
        if(($h>=0 && $h<=20) || ($h>310 && $h<=360)){
            //红色
            return 'red';
        }elseif($h>20 && $h<=35){
            //橙色
            return 'orange';
        }elseif($h>35 && $h<=75){
            //黄色
            return 'yellow';
        }elseif($h>75 &&  $h<=160){
            //绿色
            return 'green';
        }elseif($h>160 && $h<=200){
            //青色
            return 'cyan';
        }elseif($h>200  && $h<=260){
            //蓝色
            return 'blue';
        }elseif($h>260 && $h<=310){
            //紫色
            return 'purple';
        }
    }else{
        //判断黑白灰
        if($v>90){
            //白色
            return 'white';
        }else if($v<25){
            //黑色
            return 'black';
        }else{
            //灰色
            return 'coffee';
        }
    }
}


function RGB_TO_HSV ($R, $G, $B) // RGB Values:Number 0-255
{                                 // HSV Results:Number 0-1
    $HSL = array();
    $var_R = ($R / 255);
    $var_G = ($G / 255);
    $var_B = ($B / 255);
    $var_Min = min($var_R, $var_G, $var_B);
    $var_Max = max($var_R, $var_G, $var_B);
    $del_Max = $var_Max - $var_Min;
    $V = $var_Max;
    if ($del_Max == 0){
        $H = 0;
        $S = 0;
    }else{
        $S = $del_Max / $var_Max;
        $del_R = ( ( ( $var_Max - $var_R ) / 6 ) + ( $del_Max / 2 ) ) / $del_Max;
        $del_G = ( ( ( $var_Max - $var_G ) / 6 ) + ( $del_Max / 2 ) ) / $del_Max;
        $del_B = ( ( ( $var_Max - $var_B ) / 6 ) + ( $del_Max / 2 ) ) / $del_Max;
        if ($var_R == $var_Max) $H = $del_B - $del_G;
        else if ($var_G == $var_Max) $H = ( 1 / 3 ) + $del_R - $del_B;
        else if ($var_B == $var_Max) $H = ( 2 / 3 ) + $del_G - $del_R;
        if ($H<0) $H++;
        if ($H>1) $H--;
    }
    $HSL['H'] = $H;
    $HSL['S'] = $S;
    $HSL['V'] = $V;
    return $HSL;
}

function xml_to_array ($xml)
{
    $obj = simplexml_load_string($xml,"SimpleXMLElement", LIBXML_NOCDATA);
    return json_decode(json_encode($obj),true);
}